package com.rocpenghua.excel.water;


import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author pengp
 * @date 2022年07月18日 14:04
 */
public class ExcelWaterRemarkXssfUtils {
    public static void putWaterRemarkToExcel(XSSFWorkbook wb, XSSFSheet sheet, BufferedImage bufferImg) throws IOException {
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        if (null == bufferImg) {
            throw new RuntimeException("向Excel上面打印水印，读取水印图片失败(2)。");
        }
        ImageIO.write(bufferImg, "png", byteArrayOut);
        byte[] bytes = byteArrayOut.toByteArray();
        int pictureIdx = wb.addPicture(bytes, XSSFWorkbook.PICTURE_TYPE_PNG);

        //add relation from sheet to the picture data
        String rID = sheet.addRelation(null, XSSFRelation.IMAGES, wb.getAllPictures().get(pictureIdx))
                .getRelationship().getId();
        //set background picture to sheet
        sheet.getCTWorksheet().addNewPicture().setId(rID);
    }
    public static void putWaterRemarkToExcel(XSSFWorkbook wb, XSSFSheet sheet, List<String> content) throws IOException {
        BufferedImage bufferImg = ImageUtils.createWaterMark(content,new ImageParam());
        putWaterRemarkToExcel(wb,sheet,bufferImg);
    }
}
